﻿using System;
using System.Runtime.Caching;
namespace CommandLib
{
    /// <summary>
    /// 封密内存缓存类
    /// </summary>
    public sealed class MemoryCacheHelper
    {
        /// <summary>
        /// 缓存主体
        /// </summary>
        private static ObjectCache mycache = MemoryCache.Default;
        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns>object</returns>
        public static object GetData(string key)
        {
            if (!string.IsNullOrEmpty(key))
            {
                return mycache.Get(key);
            }
            else return null;
        }
        /// <summary>
        /// 添加或更新缓存数据
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void Add(string key, object value)
        {

            if (!string.IsNullOrEmpty(key))
            {
                if (mycache[key] != null)
                {
                    mycache.Set(key, value, null);
                }
                else
                    mycache.Add(key, value, null);
            }

        }
        /// <summary>
        /// 添加更新缓存数据，并通过时间间隔清除缓存
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="timespan">缓存生命周期</param>
        public static void Add(string key, object value, TimeSpan timespan)
        {

            if (!string.IsNullOrEmpty(key))
            {
                if (mycache[key] != null)
                {
                    mycache.Set(key, value, DateTimeOffset.Parse(DateTime.Now.Add(timespan).ToString()));
                }
                else

                    mycache.Add(key, value, DateTimeOffset.Parse(DateTime.Now.Add(timespan).ToString()));
            }
        }
       
        /// <summary>
        /// 移除指定键缓存
        /// </summary>
        /// <param name="key">键</param>
        public static void Remove(string key)
        {
            if (!string.IsNullOrEmpty(key))
            {
                mycache.Remove(key);
            }

        }


        /// <summary>
        /// 清除所有缓存，慎用（此方法会清除所有缓存内容）
        /// </summary>
        public static void Clear()
        {
            foreach (var item in mycache)
            {
                mycache.Remove(item.Key);
            }

        }
    }
}
